package person.lance.file;

import java.io.*;

public class FileUtil {

    public static void listFiles(File file) {
        String[] files = file.list();
        for (String str : files) {
            System.out.println(str);
        }
    }

    public static void removeFile(File file) {
        if (!file.exists()) {
            System.out.println("is not exists");
            return;
        }

        if (!file.isFile()) {
            System.out.println("not a file");
            return;
        }


        if (file.delete()) {
            System.out.println("delete success");
        } else {
            System.out.println("delete fail");
        }
    }


    public static void copyFile(File from, File to) throws IOException {

        if (!from.exists()) {
            System.out.println("file is not exists");
            return;
        }
        if (!to.exists()) {
            if (!to.getParentFile().exists()) {
                to.getParentFile().mkdirs();
            }
            to.createNewFile();
        }
        if (!from.isFile()) {
            System.out.println("The source file address is not a file");
            return;
        } else if (!to.isFile()) {
            System.out.println("The target file address is not a file");
            return;
        }


        FileInputStream fis = new FileInputStream(from);
        FileOutputStream fos = new FileOutputStream(to);

        BufferedInputStream bis = new BufferedInputStream(fis);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        byte[] buf = new byte[1024];

        while ((bis.read(buf)) != -1) {
            bos.write(buf, 0, buf.length);
        }

        bos.flush();
        bis.close();
        bos.close();
    }

    public static void copyDirectory(File from, File to) throws IOException {
        if (!from.exists()) {
            System.out.println("Direcory is not exists");
        }
        if (!from.isDirectory()) {
            System.out.println("The source directory address is not a directory");
            return;
        } else if (!to.isDirectory()) {
            System.out.println("The target directory address is not a directory");
        }

        //do copy directory
        doCopyDirectory(from, new File(to.getAbsoluteFile() + "//" + from.getName()));
    }

    private static void doCopyDirectory(File from, File to) throws IOException {
        if (from.isDirectory()) {
            File[] files = from.listFiles();
            for (File file : files) {
                doCopyDirectory(file, new File(to.getAbsoluteFile() + "//" + file.getName()));
            }
        } else {
            copyFile(from, to);
        }
    }


}
